package cn.tedu.sk.config;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    public SecurityConfig() {
        log.debug("创建springsecurity配置类对象");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 禁用“防止伪造的跨域攻击”的防御机制
        http.csrf().disable();

        // 允许复杂请求的跨域访问
        http.cors();
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                log.warn("Spring Security捕获到异常");
                String message = "当前用户未登录";
                log.warn("{}", message);
                response.sendRedirect("hi.html");
//                response.setContentType("application/json; charset=utf-8");
//                PrintWriter writer = response.getWriter();
//               // JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERROR_UNAUTHORIZED, message);
//                String jsonString = JSON.toJSONString(message);
//                writer.println(jsonString);
//                writer.close();

            }
        });

        // 黑名单！！！
        // 使用1个星号，表示通配此层级的任意资源，例如：/admins/*，可以匹配：/admins/add-new、/admins/delete
        // 但是，不可以匹配多个层级，例如：/admins/*，不可以匹配：/admins/9527/delete
        // 使用2个连续的星号，表示通配若干层级的任意资源，例如：/admins/*，可以匹配：/admins/add-new、/admins/9527/delete
        String[] urls = {
                "/hi"
        };

        http.authorizeRequests()
                .mvcMatchers(urls)
                .authenticated()
                .anyRequest()
                .permitAll();

    }





}
